/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.execute.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.ExecuteConstant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteCompleteRequestDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteCompleteSaveDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.execute.enums.ExecuteStateEnum;
import com.icinfo.cloud.provider.punish.execute.mapper.*;
import com.icinfo.cloud.provider.punish.execute.model.*;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteCompleteRecordService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocCommonOperateService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteFlowRecordService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteMainInfoService;
import com.icinfo.cloud.provider.punish.execute.vo.ExecuteCompleteVo;
import com.icinfo.cloud.provider.punish.execute.vo.ExecuteStageLinkRelateDocumentVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 裁执分离-执行完毕信息 execute_complete_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年09月06日
 */
@Service
@Slf4j
public class ExecuteCompleteRecordServiceImpl extends MyBatisServiceSupport implements IExecuteCompleteRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ExecuteCompleteRecordServiceImpl.class);

    @Resource
    private ExecuteCompleteRecordMapper executeCompleteRecordMapper;
    @Resource
    private ExecuteAppendixRecordMapper executeAppendixRecordMapper;
    @Resource
    private IExecuteMainInfoService executeMainInfoService;
    @Resource
    private ExecuteMainInfoMapper executeMainInfoMapper;
    @Resource
    private IExecuteFlowRecordService executeFlowRecordService;
    @Resource
    private ExecuteFilesRecordMapper executeFilesRecordMapper;
    @Resource
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;
    @Resource
    private IExecuteDocCommonOperateService executeDocCommonOperateService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCompleteInfo(ExecuteCompleteSaveDto saveDto) {
        int updateCount=0;
        UserDTO userDTO = UserUtil.getUserInfo();
        if (userDTO == null) {
            throw new BusinessException("登录信息失效或未登录!");
        }
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(saveDto.getExecuteId());
        //受案和结案阶段不能进行该操作
        if(ExecuteStateEnum.CASE_CLOSED.getCode().equals(executeMainInfo.getExecuteState())
                || ExecuteStateEnum.ACCEPT_CASE.getCode().equals(executeMainInfo.getExecuteState())){
            throw new BusinessException("当前阶段不能执行该操作!");
        }
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDocumentInfoByDocumentKindCode(null, "ZXQKHCJL");

        Example example = new Example(ExecuteDocumentRecord.class);
        example.createCriteria().andEqualTo("executeId",saveDto.getExecuteId()).
                andEqualTo("documentCatalogCode",configBusiParamDocumentInfo.getDocumentCatalogCode());
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(example);
        //已经生成核查记录文书，执行完成阶段已经结束
        if(executeDocumentRecords != null && executeDocumentRecords.size()>0){
            new BusinessException("强制执行已结束!");
        }
        Example completeExample = new Example(ExecuteCompleteRecord.class);
        completeExample.createCriteria().andEqualTo("executeId",saveDto.getExecuteId()).
                andEqualTo("isDelete",Constant.STRING_0);
        int completeCount = executeCompleteRecordMapper.selectCountByExample(completeExample);
        if(completeCount>0){
            //删除原执行完毕信息记录
            executeCompleteRecordMapper.deleteByExample(completeExample);
        }
        ExecuteCompleteRecord completeRecord = new ExecuteCompleteRecord();
        BeanUtils.copyProperties(saveDto,completeRecord);
        completeRecord.setId(StringUtils.uuid());
        completeRecord.setCreateTime(new Date());
        completeRecord.setCreateUserId(String.valueOf(userDTO.getUserId()));
        completeRecord.setCreateUserName(userDTO.getRealName());
        //新增
        updateCount= executeCompleteRecordMapper.insertSelective(completeRecord);
        //修改主表状态
        String nextExecuteState;
        String currentExecuteState = executeMainInfo.getExecuteState();
        //executeMainInfo.setExecuteState(ExecuteStateEnum.CASE_CLOSED.getCode());
        //nextExecuteState = ExecuteStateEnum.CASE_CLOSED.getCode();
        //修改主表阶段信息
        //Example executeMainInfoUpdateExample = new Example(ExecuteMainInfo.class);
        //executeMainInfoUpdateExample.createCriteria().andEqualTo("executeId",saveDto.getExecuteId());
        //updateCount = executeMainInfoMapper.updateByExample(executeMainInfo,executeMainInfoUpdateExample);

        //删除附件信息和执行凭证附件
        Example appendixExample = new Example(ExecuteAppendixRecord.class);
        appendixExample.createCriteria().andEqualTo("executeId",saveDto.getExecuteId()).
                andEqualTo("isDelete",Constant.STRING_0).
                andEqualTo("executeStageCode","QZZX");
        executeAppendixRecordMapper.deleteByExample(example);
        //保存执行凭证
        if(saveDto.getVoucherList() != null && saveDto.getVoucherList().size()>0){
            dealAppendixRecordList(saveDto.getVoucherList(),saveDto.getExecuteId(),ExecuteConstant.EXECUTE_LINK_QZZXWB_ZXQKPZ,ExecuteConstant.EXECUTE_LINK_QZZXWB_ZXQKPZ_STR);
        }
        if(updateCount > 0){
            //生成执行情况核查记录文书
            ExecuteDocCommonOperateSaveDto docSaveDto = new ExecuteDocCommonOperateSaveDto();
            docSaveDto.setExecuteId(saveDto.getExecuteId());
            docSaveDto.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
            HashMap<String, Object> dataMap =new HashMap<>();
            dataMap.put("completeTime",new Date());
            dataMap.put("completeDesc",saveDto.getCompleteDesc());
            docSaveDto.setDataMap(dataMap);
            if(saveDto.getAppendixList() != null && saveDto.getAppendixList().size()>0){
                docSaveDto.setAppendixList(saveDto.getAppendixList());
            }
            Map<String, Object> resultMap = executeDocCommonOperateService.saveDocInfo(docSaveDto);
        }
        return updateCount > 0 ? true : false;
    }
    private void dealAppendixRecordList(List<AppendixDto> appendixList,String executeId,String linkCode,String linkName){
        UserDTO userDTO = UserUtil.getUserInfo();
        if (userDTO == null) {
            throw new BusinessException("登录信息失效或未登录!");
        }
        for (AppendixDto appendixDto:appendixList) {
            ExecuteAppendixRecord appendixRecord = new ExecuteAppendixRecord();
            appendixRecord.setId(StringUtils.uuid());
            appendixRecord.setExecuteId(executeId);
            appendixRecord.setExecuteStageCode(ExecuteStateEnum.ENFORCE.getCode());
            appendixRecord.setExecuteStageName(ExecuteStateEnum.ENFORCE.getDes());
            //设置强制执行完毕
            appendixRecord.setExecuteLinkCode(linkCode);
            appendixRecord.setExecuteLinkName(linkName);
            appendixRecord.setAppendixName(appendixDto.getAppendixName());
            appendixRecord.setAppendixUrl(appendixDto.getAppendixUrl());
            appendixRecord.setAppendixName(appendixDto.getAppendixName());
            appendixRecord.setUploadTime(new Date());
            appendixRecord.setUploadUserId(userDTO.getUserId().toString());
            appendixRecord.setUploadUserName(userDTO.getRealName());
            appendixRecord.setIsDelete(Constant.STRING_0);
            appendixRecord.setAppendixStatus(Constant.STRING_1);
            appendixRecord.setAppendixType("执行情况凭证");
            executeAppendixRecordMapper.insertSelective(appendixRecord);
        }
    }

    @Override
    public ExecuteCompleteVo getCompleteInfo(ExecuteCompleteRequestDto saveDto) {
        ExecuteCompleteVo vo = new ExecuteCompleteVo();
        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(saveDto.getExecuteId());
        BeanUtils.copyProperties(executeMainInfo,vo);
        Example example = new Example(ExecuteCompleteRecord.class);
        example.createCriteria().andEqualTo("executeId",saveDto.getExecuteId());
        List<ExecuteCompleteRecord> executeCompleteRecords = executeCompleteRecordMapper.selectByExample(example);
        if(executeCompleteRecords != null && executeCompleteRecords.size()>0){
            ExecuteCompleteRecord executeCompleteRecord = executeCompleteRecords.get(0);
            BeanUtils.copyProperties(executeCompleteRecord,vo);
        }else {
            vo.setRuleNumber(executeMainInfo.getRuleNumber());
        }
        //裁决书附件信息
        List<ExecuteStageLinkRelateDocumentVo> ruleNumberFile = executeFilesRecordMapper.selectRuleNumberFiles(saveDto.getExecuteId());
        vo.setRuleNumberFile(ruleNumberFile);
        //设置裁定书附件信息
        Example ruleNumberExample = new Example(ExecuteFilesRecord.class);
        ruleNumberExample.createCriteria().andEqualTo("executeId",saveDto.getExecuteId()).
                andEqualTo("fileTypeId",Constant.STRING_1);
        List<ExecuteFilesRecord> ruleNumberFilesRecord = executeFilesRecordMapper.selectByExample(ruleNumberExample);
        if(ruleNumberFilesRecord != null && ruleNumberFilesRecord.size()>0){
            vo.setRuleNumberUrl(ruleNumberFilesRecord.get(0).getFileUrl());
        }

        return vo;
    }

    @Override
    public ExecuteCompleteRecord getExecuteCompleteRecordByExecuteId(String executeId) {
        Example example = new Example(ExecuteCompleteRecord.class);
        example.createCriteria().andEqualTo("executeId", executeId);
        List<ExecuteCompleteRecord> executeCompleteRecords  = executeCompleteRecordMapper.selectByExample(example);
        if (null != executeCompleteRecords && executeCompleteRecords.size() > 0) {
            ExecuteCompleteRecord executeCompleteRecord = executeCompleteRecords.get(0);
            return executeCompleteRecord;
        } else {
            throw new BusinessException("未获取到参照分离完结信息-executeId:"+executeId);
        }
    }

}